import 'package:basic_library/basic_library.dart';
import 'package:flutter/material.dart';

///
/// 包含头像，右角标数的 button - 消息
///
class QMessageAvatarNumButton extends StatelessWidget {
  final String avatarUrl;
  final String placeholder;
  final int count;
  final double? height;
  final GestureTapCallback? tapCallback;

  const QMessageAvatarNumButton({
    Key? key,
    required this.avatarUrl,
    required this.placeholder,
    this.count = 0,
    this.height,
    this.tapCallback,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (tapCallback != null) {
          tapCallback!();
        }
      },
      child: Row(
        children: [
          Stack(
            children: [
              /// 头像
              Positioned(
                child: Container(
                  constraints: BoxConstraints(
                      maxHeight: height ?? 45, maxWidth: height ?? 45),
                  margin: const EdgeInsets.symmetric(vertical: 6),
                  child: // 头像，可以替换为用户相关的头像url
                  ClipRRect(
                    borderRadius: BorderRadius.circular(5),
                    child: MyNetWorkImage(
                      url: avatarUrl,
                      width: double.infinity,
                      height: height ?? 45,
                      fit: BoxFit.cover,
                      placeHolderWidget: Image.asset(
                        placeholder,
                        width: height ?? 45,
                        height: height ?? 45,
                      ),
                    ),
                  ),
                ),
              ),

              /// 未读数
              Positioned(
                top: 0,
                right: 0,
                child: unreadCountWidget(
                  count,
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

/// 未读数
unreadCountWidget(int unreadCount) {
  if (unreadCount == 0) return Container();
  String count;
  if (unreadCount > 99) {
    count = '99+';
  } else {
    count = unreadCount.toString();
  }
  return Container(
    padding: const EdgeInsets.only(left: 3, right: 3),
    decoration: const BoxDecoration(
      color: Colors.red,
      borderRadius: BorderRadius.all(
        Radius.circular(15),
      ),
    ),
    constraints: const BoxConstraints(
      minWidth: 18,
      maxWidth: 30,
    ),
    child: Text(
      count,
      maxLines: 1,
      textAlign: TextAlign.center,
      style: const TextStyle(
        fontSize: 12,
        color: Colors.white,
      ),
    ),
  );
}
